package org.javaforever.infinity.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.javaforever.infinity.compiler.SGSCompiler;
import org.javaforever.infinity.domain.Project;

/**
 * Servlet implementation class GenerateSampleCodeController
 */

public class GenerateSampleCodeController extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GenerateSampleCodeController() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			PrintWriter out = response.getWriter();
			String sourcefolder = request.getSession().getServletContext().getRealPath("/")+"source/";
			sourcefolder = sourcefolder.replace('\\', '/');
			
			String sgscode = request.getParameter("code");
			System.out.println(sgscode);
			Project project = SGSCompiler.translate(sgscode);
			
			System.out.println(sourcefolder);
			project.setFolderPath(sourcefolder);
			project.setSourceFolderPath((request.getSession().getServletContext().getRealPath("/")+"templates/").replace('\\', '/'));
			
			project.generateProjectZip();
					
			request.setAttribute("zipfile", project.getStandardName());
	    	request.getRequestDispatcher("../jsp/download.jsp").forward(request, response);
		} catch(Exception e){
			e.printStackTrace();
			request.getRequestDispatcher("../jsp/index.jsp").forward(request, response);
		}
	 }

}
